package com.gitee.funcy.multiple.datasource.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.Optional;
import java.util.stream.Stream;

/**
 * ｛这里添加描述｝
 *
 * @author funcy
 * @date 2019-08-24 16:10
 */
public class ResourceUtil {

    private static PathMatchingResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();

    public static Resource[] getPathMatchingResource(String classpathUri) {
        if(StringUtils.isEmpty(classpathUri)) {
            return new Resource[0];
        }
        String[] uriArray = classpathUri.split(",");
        if(null == uriArray || uriArray.length == 0) {
            return new Resource[0];
        }
        return Stream.of(Optional.ofNullable(uriArray).orElse(new String[0]))
                .flatMap(location -> Stream.of(getResources(location)))
                .toArray(Resource[]::new);
    }

    private static Resource[] getResources(String location) {
        try {
            return resourceResolver.getResources(StringUtils.trimToEmpty(location));
        } catch (IOException e) {
            return new Resource[0];
        }
    }

}
